<?php
/////////////////////////// DATABASE FUNCTIONS ////////////////////////////////////

// OPEN THE DATASOURCE FILE AND GET THE APPROPRIATE FIELD
function GetDataSource()
{
	$filename = $_SERVER['DOCUMENT_ROOT']."/dao/datasource.dat";
	$fp = fopen($filename, "r");
	$file_contents = fread($fp, filesize($filename));
	fclose($fp);

	$datasource_array = explode("\n", $file_contents);

	$data_pair = explode(":", $datasource_array[0]);
	return $data_pair;
}

// THIS FUNCTION CONNECTS TO THE MAIN DATABASE
function ConnectMainDatabase()
{
	$data_pair = GetDataSource();

	$DataSource = trim($data_pair[0]);
	$DataUser = trim($data_pair[1]);
	$DataPass = trim($data_pair[2]);
	$DB = trim($data_pair[4]);
	
	$connectstring = mysql_connect($DataSource, $DataUser, $DataPass) or die("Failed to connect MySQL");
	mysql_select_db($DB, $connectstring) or die("Failed to select DB");
	return $connectstring;
}

function CloseMainDatabase($connectedstring)
{
	// This function Close the connection to the main QPREPAID Database
	mysql_close($connectedstring);

	return 1;
}

function getTableResultCount($tableName, $condition, $connStr) {
	$query = "SELECT COUNT(*) as count FROM $tableName WHERE 1 = 1";
	
	foreach ($condition as $field => $value) {
		$query .= " AND $field = '$value'";
	}
	$queryexe = mysql_query($query, $connStr);
	$data = mysql_fetch_assoc($queryexe);
	
	return $data['count'];
	
}

function getFieldFromTable($tableName, $fieldName, $connStr){
	
	$query = "SELECT $fieldName FROM $tableName";
	$queryexe = mysql_query($query, $connStr);
	$result = mysql_fetch_row($queryexe);
	
	return $result[0];
}

?>
